<?php

	class framework
	{

		var $template	= false;
		var $main_template = 'main.template.tpl';
		var $content	= false;

		var $do			= null;

		var $config		= array();
		var $prefrences	= array();

		var $sql		= null;

		var $referer	= 'index.php';

		var $pc			= null;

		var $js			= array('common.js');

		var $queries	= array();

		var $npp		= 20; // number per page. Used when pagniation is applied to a list.

		function framework($db_host, $db_user, $db_pass, $db_name, $db_prefix)
		{

			@set_magic_quotes_runtime(0);

			mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
			mysql_select_db($db_name);

			$this->_prefix			= $db_prefix;
			$this->_parse_prefix	= '#__';

			$this->do				= isset($_REQUEST['do']) ? $_REQUEST['do'] : null;

			$this->config			= $this->get_config();

			$this->referer			= @$_SERVER['HTTP_REFERER'];

			// Paper Chain
			$this->pc_item('Home', 'Return to the homepage', 'index.php');

			if(get_magic_quotes_gpc() === 1)
			{

				// This will remove slashes from GPC

				if(!empty($_GET))		$_GET		= array_map('remove_gpc_slashes', $_GET);
				if(!empty($_POST))		$_POST		= array_map('remove_gpc_slashes', $_POST);
				if(!empty($_COOKIE)) 	$_COOKIE	= array_map('remove_gpc_slashes', $_COOKIE);
				if(!empty($_REQUEST)) 	$_REQUEST	= array_map('remove_gpc_slashes', $_REQUEST);

			}

		}

		// remove all files from a directory
		function clean_dir($path) {
			if(is_dir($path) && is_readable($path)) {
				$dh = opendir($path);
				if($dh) {
					while(($file = readdir($dh)) !== false) {
						if($file{0} != '.') {
							unlink($path . $file);
						}
					}
				}
				unset($dh, $file);
			}
		}

		function unlink($file) {
			if(file_exists($file) && is_writeable($file)) {
				return unlink($file);
			}
			return false;
		}

		// Checks that the supplied email address is valid
		function is_email($email)
		{
			if(preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $email)) {
				return true;
			}
			return false;
		}

		// checks if the provided member username is valid
		function is_username($username)
		{
			if(preg_match("/^[a-z0-9_-]{3,20}$/i", $username)) {
				return true;
			}
			return false;
		}

		// get a list of the tables within MM
		function db_get_tables()
		{

			$sql	= $this->_pq("SHOW TABLE STATUS LIKE '". $this->_prefix ."%'");
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_row($result))
			{

				$results[] = $row[0];

			}

			return isset($results) ? $results : false;

		}

		// based on the number of records, generates all the numbered needed to build up a paginated display of data
		function pagination($num_records)
		{
			$page	= isset($_REQUEST['page']) ? (int)$_REQUEST['page'] : 1;
			$pages	= ceil($num_records / $this->npp);

			if($page < 1 || $page > $pages) $page = 1;

			$start	= ($page - 1) * $this->npp;
			$limit	= $this->npp;
			return array('num' => $num_records, 'page' => $page, 'pages' => $pages, 'start' => $start, 'limit' => $limit);
		}

		function pc_item($name, $desc, $href = null)
		{

			$this->pc[] = array($name, $desc, $href);

		}

		function pc_build($sep = '&gt;')
		{

			$tmp = $this->pc;
			$this->pc = null;

			for($i = 0; $i < count($tmp); $i++)
			{

				$v = $tmp[$i];
				$title = str_replace('&', '&amp;', $v[1]);

				if($v[2] !== null)
				{

					$href = str_replace('&', '&amp;', $v[2]);

					$this->pc .= '<a href="'. $href .'" title="'. $title .'">'. strtolower($v[0]) .'</a>';

				}
				else
				{

					$this->pc .= '<span title="'. $title .'">'. strtolower($v[0]) .'</span>';

				}

				if($i < count($tmp) - 1)
				{

					$this->pc .= ' '. $sep .' ';

				}


			}

			return $this->pc;

		}

		function add_cast_member($imdb_id, $name)
		{

			// Firstly check if this cast member already exists
			$sql	= $this->_pq("SELECT name_id FROM #__cast WHERE name_imdb = '%s';", $imdb_id);
			$result	= mysql_query($sql) or die(mysql_error());

			if(mysql_num_rows($result) == 0)
			{

				$sql	= $this->_pq("INSERT INTO #__cast (name_imdb, name_name) VALUES ('%s', '%s');", $imdb_id, $name);
				$result	= mysql_query($sql) or die(mysql_error());

				if($result) return mysql_insert_id();

			}
			elseif(mysql_num_rows($result) == 1)
			{

				return mysql_result($result, 0, 0);

			}

			return false;

		}

		// return an array of movies the selected member is borrowing off other people
		function get_borrowing($member_id)
		{

			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, m.movie_year, m.movie_imdb, b.borrow_borrowed_date, b.borrower_id, b.borrow_contact_name, b.borrow_contact_email, b.own_id FROM #__borrow b INNER JOIN #__movies m ON m.movie_id = b.movie_id WHERE b.borrower_id = %s", $member_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_assoc($result))
			{

				$results[]	= array('id'		=> $row['movie_id'],
									'title'		=> $row['movie_title'],
									'year'		=> $row['movie_year'],
									'imdb'		=> $row['movie_imdb'],
									'imdb_url'	=> $this->imdb_url($row['movie_imdb']));

			}

			return isset($results) ? $results : false;

		}

		// Return an array of movies people are currently borrowing off the selected member_id
		function get_borrowed($member_id)
		{

			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, m.movie_year, m.movie_imdb, mem.member_id, mem.member_username, mem.member_email, b.borrow_borrowed_date, b.borrower_id, borrow_contact_name, borrow_contact_email, b.own_id FROM #__movies m INNER JOIN #__borrow b ON m.movie_id = b.movie_id LEFT OUTER JOIN #__member mem ON b.borrower_id = mem.member_id AND mem.member_active = 1 WHERE b.owner_id = %s AND b.borrow_status = 'borrowed' ORDER BY borrow_borrowed_date DESC", (int)$member_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$is_member	= ($row['borrower_id'] !== null ? true : false);

				$results[]	= array('id'		=> $row['movie_id'],
									'title'		=> $row['movie_title'],
									'year'		=> $row['movie_year'],
									'imdb'		=> $row['movie_imdb'],
									'imdb_url'	=> $this->imdb_url($row['movie_imdb']),
									'own_id'	=> $row['own_id'],
									'is_member'	=> $is_member,
									'member_id'	=> ($is_member ? $row['member_id'] : null),
									'username'	=> ($is_member ? $row['member_username'] : $row['borrow_contact_name']),
									'email'		=> ($is_member ? $row['member_email'] : $row['borrow_contact_email']),
									'borrowed'	=> $row['borrow_borrowed_date']);

			}

			return isset($results) ? $results : false;

		}

		function get_available_templates()
		{

			// Returns an array of the available templates(smarty) that can be used
			$handle = opendir(_BASE_PATH .'/templates/');

			if($handle)
			{

				while(($file = readdir($handle)) !== false)
				{

					if($file{0} != '.' && is_dir(_BASE_PATH .'/templates/'. $file .'/'))
					{

						$results[$file] = ucwords(str_replace('_', ' ', $file));

					}

				}

				closedir($handle);

			}

			return isset($results) ? $results : false;

		}

		// Obtain a list of actors within the selected movie
		function get_cast_actors_from_movie($movie_id)
		{

			$sql	= $this->_pq("SELECT a.name_id, c.name_imdb, a.mc_character_name, a.mc_credited_as FROM #__lnk_movie_actors a INNER JOIN #__cast c ON a.name_id = c.name_id WHERE a.movie_id = %s", (int)$movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_assoc($result))
			{

				$results[]	= array('id'		=> $row['name_id'],
									'imdb_id'	=> $row['name_imdb'],
									'imdb_url'	=> $this->imdb_cast_url($row['name_imdb']),
									'character'	=> $row['mc_character_name'],
									'credited'	=> $row['mc_credited_as']);

			}

			return isset($results) ? $results : false;

		}

		// Obtain a list of directors within the selected movie
		function get_cast_directors_from_movie($movie_id)
		{

			$sql	= $this->_pq("SELECT c.name_id, c.name_imdb, c.name_name FROM #__lnk_movie_directors d INNER JOIN #__cast c ON d.name_id = c.name_id WHERE d.movie_id = %s", (int)$movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_assoc($result))
			{

				$results[]	= array('id'		=> $row['name_id'],
									'imdb_id'	=> $row['name_imdb'],
									'imdb_url'	=> $this->imdb_cast_url($row['name_imdb']),
									'credited'	=> $row['name_name']);

			}

			return isset($results) ? $results : false;

		}

		// Obtain a list of writers within the selected movie
		function get_cast_writers_from_movie($movie_id)
		{

			$sql	= $this->_pq("SELECT c.name_id, c.name_imdb, c.name_name, w.mw_role FROM #__lnk_movie_writers w INNER JOIN #__cast c ON w.name_id = c.name_id WHERE w.movie_id = %s", (int)$movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_assoc($result))
			{

				$results[]	= array('id'		=> $row['name_id'],
									'imdb_id'	=> $row['name_imdb'],
									'imdb_url'	=> $this->imdb_cast_url($row['name_imdb']),
									'credited'	=> $row['name_name'],
									'role'		=> $row['mw_role']);

			}

			return isset($results) ? $results : false;

		}

		function get_config()
		{

			// Produce an array of all the db configuration options

			$sql	= $this->_pq("SELECT config_key, config_value FROM #__config ORDER BY config_key ASC");
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[$row['config_key']] = $row['config_value'];

			}

			return isset($results) ? $results : false;

		}

		function get_genres()
		{

			// Return a list of the available genres
			$sql	= $this->_pq("SELECT g.genre_id, g.genre_name, g.genre_movie_count as movies FROM #__genre g ORDER BY g.genre_name ASC");
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'			=> $row['genre_id'],
									'name'			=> $row['genre_name'],
									'movie_count'	=> $row['movies']);

			}

			return isset($results) ? $results : false;

		}

		// count the number of movies in a genre
		function get_count_movies_in_genre($id, $filter = null, $search = null)
		{
			$where	= array();
			if($filter !== null) {
				$where[] = $this->_sql_filter('`m`.`movie_title`', $filter);
			}
			if($search !== null) {
				$where[] = "`m`.`movie_title` LIKE '%%". $search ."%%' ";
			}
			$where = (count($where) > 0) ? "AND ". implode(" AND ", $where) : null;

			$sql	= $this->_pq("SELECT COUNT(DISTINCT `m`.`movie_id`) FROM `#__movies` `m` INNER JOIN `#__lnk_movie_genre` `mg` ON `m`.`movie_id` = `mg`.`movie_id` WHERE `mg`.`genre_id` = %s $where", (int)$id);
			$result	= mysql_query($sql) or die(mysql_error());

			if($count = mysql_result($result, 0, 0)) {
				return $count;
			}
			return false;
		}

		function get_genre_movies($id, $filter = null, $search = null, $limits = null)
		{

			// Get all the movies for a specific genre

			$member_id	= (int)$this->security->dtls['id'];
			$where		= array();

			if($filter !== null) {
				$where[] = $this->_sql_filter('m.movie_title', $filter);
			}

			if($search !== null) {
				$where[] = "m.movie_title LIKE '%%$search%%' ";
			}

			if($limits !== null && isset($limits['limit'])) {
				$limit = "LIMIT ";
				if(isset($limits['start'])) {
					$limit .= (int)$limits['start'] .", ";
				}
				$limit .= (int)$limits['limit'];
			} else {
				// double check
				$limit = null;
			}

			$where	= (count($where) > 0) ? "AND ". implode(" AND ", $where) : null;
			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, m.movie_imdb, m.movie_year, COUNT(o.movie_id) as owners FROM #__movies m INNER JOIN #__lnk_movie_genre mg ON m.movie_id = mg.movie_id LEFT OUTER JOIN #__own o ON m.movie_id = o.movie_id WHERE mg.genre_id = '%s' $where GROUP BY m.movie_id ORDER BY m.movie_title ASC $limit", $id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'			=> $row['movie_id'],
									'title'			=> $row['movie_title'],
									'imdb'			=> $row['movie_imdb'],
									'imdb_url'		=> $this->imdb_url($row['movie_imdb']),
									'year'			=> $row['movie_year'],
									'owners'		=> $row['owners'],
									'in_collection'	=> true,
									'in_wishlist'	=> true);

			}

			return isset($results) ? $results : false;

		}

		function get_member_details($id)
		{

			// Get all the details of the selected member

			$sql	= $this->_pq("SELECT member_id, member_username, member_email, member_active, member_approved, member_approved_date, referer_id, last_login, movie_count, is_referer, pref_public_collection, pref_imdb_window FROM #__member WHERE member_id = '%s'", $id);
			$result	= mysql_query($sql) or die(mysql_error());

			if(mysql_num_rows($result) == 1 && $row = mysql_fetch_array($result))
			{

				$results	= array('id'			=> (int)$row['member_id'],
									'username'		=> $row['member_username'],
									'email'			=> $row['member_email'],
									'active'		=> (int)$row['member_active'] == 1 ? true : false,
									'approved'		=> (int)$row['member_approved'] == 1 ? true : false,
									'approve_date'	=> (int)$row['member_approved_date'],
									'referer'		=> (int)$row['referer_id'],
									'last_login'	=> (int)$row['last_login'],
									'movie_count'	=> (int)$row['movie_count'],
									'is_referer'	=> (int)$row['is_referer'],
									'preference'		=> array('imdb_open_window' => (int)$row['pref_imdb_window'],
															'public_collection' => (int)$row['pref_public_collection']));

			}

			return isset($results) ? $results : false;

		}

		//count the number of movies in a members collection
		function get_count_movies_in_member($id, $filter = null, $search = null, $genre = null)
		{
			$where = array();
			if($filter !== null && !empty($filter)) {
				$where[] = $this->_sql_filter('m.movie_title', $filter);
			}

			if($search !== null && !empty($search)) {
				$where[] = "m.movie_title LIKE '%%". addslashes($search) ."%%' ";
			}

			if($genre !== null && is_numeric($genre) && !empty($genre)) {
				$where[] = "l.genre_id = ". $genre;
			}
			$where	= (count($where) > 0) ? "AND ". implode(" AND ", $where) : null;

			$sql	= $this->_pq("SELECT COUNT(DISTINCT m.movie_id) FROM #__movies m INNER JOIN #__own o ON m.movie_id = o.movie_id INNER JOIN #__lnk_movie_genre l ON m.movie_id = l.movie_id WHERE member_id = '$id' $where");
			$result	= mysql_query($sql) or die(mysql_error());
			if($count = mysql_result($result, 0, 0)) {
				return $count;
			}
			return false;
		}

		function get_member_movies($id, $filter = null, $search = null, $genre = null, $limits = null)
		{

			// Returns an array of movies in the 'my collection' of the selected member
			$where	= array();

			if($filter !== null && !empty($filter)) {
				$where[] = $this->_sql_filter('m.movie_title', $filter);
			}

			if($search !== null && !empty($search)) {
				$where[] = "m.movie_title LIKE '%%". addslashes($search) ."%%' ";
			}

			if($genre !== null && is_numeric($genre) && !empty($genre)) {
				$where[] = "l.genre_id = ". $genre;
			}

			if($limits !== null && isset($limits['limit'])) {
				$limit = "LIMIT ";
				if(isset($limits['start'])) {
					$limit .= (int)$limits['start'] .", ";
				}
				$limit .= (int)$limits['limit'];
			} else {
				// double check
				$limit = null;
			}

			$where	= (count($where) > 0) ? "AND ". implode(" AND ", $where) : null;
			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, m.movie_year, m.movie_imdb, o.own_dtls_medium, o.own_created, o.own_id, o.own_incomplete FROM #__movies m INNER JOIN #__own o ON m.movie_id = o.movie_id INNER JOIN #__lnk_movie_genre l ON m.movie_id = l.movie_id WHERE member_id = '$id' $where GROUP BY m.movie_id ORDER BY m.movie_title ASC $limit");
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result)) {
				$results[]	= array('id'			=> $row['movie_id'],
									'title'			=> $row['movie_title'],
									'year'			=> $row['movie_year'],
									'imdb'			=> $row['movie_imdb'],
									'imdb_url'		=> $this->imdb_url($row['movie_imdb']),
									'medium'		=> $row['own_dtls_medium'],
									'created'		=> $row['own_created'],
									'own_id'		=> $row['own_id'],
									'incomplete'	=> ($row['own_incomplete'] == '1' ? true : false));
			}

			return isset($results) ? $results : false;

		}

		// count the number of movies in a members wishlist
		function get_count_movies_in_wishlist($id, $filter = null, $search = null, $genre = null)
		{
			$where	= array();
			if($filter !== null && !empty($filter)) {
				$where[] = $this->_sql_filter('m.movie_title', $filter);

			}

			if($search !== null && !empty($search))
			{

				$where[] = "m.movie_title LIKE '%%". addslashes($search) ."%%' ";

			}

			if($genre !== null && !empty($genre))
			{

				$where[] = "l.genre_id = ". (int)$genre;

			}
			$where	= (count($where) > 0) ? "AND ". implode(" AND ", $where) : null;

			$sql	= $this->_pq("SELECT COUNT(DISTINCT m.movie_id) FROM #__movies m INNER JOIN #__wishlist w ON m.movie_id = w.movie_id LEFT OUTER JOIN #__own o ON m.movie_id = o.movie_id AND o.member_id != '$id' INNER JOIN #__lnk_movie_genre l ON m.movie_id = l.movie_id WHERE w.member_id = '$id' $where");
			$result	= mysql_query($sql) or die(mysql_error());
			if($count = mysql_result($result, 0, 0)) {
				return $count;
			}
			return false;
		}

		function get_member_wishlist($id, $filter = null, $search = null, $genre = null, $limits = null)
		{

			// Get the entire list of movies an a members wishlist

			$where	= array();

			if($filter !== null && !empty($filter)) {
				$where[] = $this->_sql_filter('m.movie_title', $filter);
			}

			if($search !== null && !empty($search))
			{

				$where[] = "m.movie_title LIKE '%%". addslashes($search) ."%%' ";

			}

			if($genre !== null && !empty($genre))
			{

				$where[] = "l.genre_id = ". (int)$genre;

			}

			if($limits !== null && isset($limits['limit'])) {
				$limit = "LIMIT ";
				if(isset($limits['start'])) {
					$limit .= (int)$limits['start'] .", ";
				}
				$limit .= (int)$limits['limit'];
			} else {
				// double check
				$limit = null;
			}
			$where	= (count($where) > 0) ? "AND ". implode(" AND ", $where) : null;
			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, m.movie_year, m.movie_imdb, o.member_id, w.wishlist_created FROM #__movies m INNER JOIN #__wishlist w ON m.movie_id = w.movie_id LEFT OUTER JOIN #__own o ON m.movie_id = o.movie_id AND o.member_id != '$id' INNER JOIN #__lnk_movie_genre l ON m.movie_id = l.movie_id  WHERE w.member_id = '$id' $where GROUP BY m.movie_id ORDER BY m.movie_title ASC $limit");
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'		=> $row['movie_id'],
									'title'		=> $row['movie_title'],
									'year'		=> $row['movie_year'],
									'imdb'		=> $row['movie_imdb'],
									'imdb_url'	=> $this->imdb_url($row['movie_imdb']),
									'available'	=> ($row[4] !== null ? true : false),
									'created'	=> $row['wishlist_created']);

			}

			return isset($results) ? $results : false;

		}

		function get_members($active = 1, $approved = 1, $list_self	= true, $filter = null, $search = null)
		{

			// Return a list of members
			$where	= array();

			if($filter !== null && !empty($filter)) {

				$where[]	= $this->_sql_filter('m.member_username', $filter);

			}

			if($search !== null && !empty($search))
			{

				$where[] = "(m.member_username LIKE '%%". addslashes($search) ."%%' OR m.member_email LIKE '%%". addslashes($search) ."%%')";

			}

			if($active != null)
			{

				$where[]	= "member_active = ". (int)$active;

			}

			if($approved != null)
			{

				$approved = (int)$approved;

				if($approved == 1)
				{

					$where[]	= "member_approved = 1 AND member_approved_date > 0";

				}
				else
				{

					$where[]	= "member_approved = 0 AND member_approved_date = 0";

				}

			}

			if($list_self == false) {
				$where[]	= "member_id != ". (int)$this->security->dtls['id'];
			}
			$where	= (count($where) > 0) ? "WHERE ". implode(" AND ", $where) : null;

			$sql	= $this->_pq("SELECT member_id, member_username, member_email, member_active, member_approved_date, last_login, movie_count, is_referer FROM #__member m $where ORDER BY member_username ASC");
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'			=> $row['member_id'],
									'username'		=> $row['member_username'],
									'email'			=> $row['member_email'],
									'active'		=> $row['member_active'],
									'approved'		=> $row['member_approved_date'],
									'last_login'	=> $row['last_login'],
									'movie_count'	=> $row['movie_count'],
									'referer'		=> $row['is_referer']);

			}

			return isset($results) ? $results : false;

		}

		// return a list of comments for this movie
		function get_movie_comments($movie_id)
		{

			$sql	= $this->_pq("SELECT c.comment_id, c.comment_data, c.comment_created, c.comment_active, m.member_id, m.member_username, m.member_email FROM #__comment c LEFT OUTER JOIN #__member m ON c.member_id = m.member_id WHERE movie_id = %s", (int)$movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_assoc($result))
			{

				$results[]	= array('id'		=> $row['comment_id'],
									'member_id'	=> $row['member_id'],
									'comment'	=> nl2br($row['comment_data']),
									'created'	=> $row['comment_created'],
									'active'	=> ($row['comment_active'] == 1 ? true : false),
									'member'	=> array('id' => $row['member_id'], 'username' => $row['member_username'], 'email' => $row['member_email']));

			}

			return isset($results) ? $results : false;

		}

		// return a list of details on a selected owned copy of a movie
		function get_movie_own_details($own_id)
		{

			$sql	= $this->_pq("SELECT `o`.`member_id`, `o`.`movie_id`, `o`.`own_dtls_medium`, 
								`o`.`own_dtls_format`, `o`.`own_dtls_ratio`, `o`.`own_dtls_language`, 
								`o`.`own_dtls_subtitle`, `o`.`own_dtls_sound`, `o`.`own_dtls_comment`, 
								`o`.`own_rating`, `o`.`own_created`, `o`.`own_updated`, 
								`o`.`own_incomplete` 
								FROM `#__own` `o` 
								WHERE `o`.`own_id` = %s", (int)$own_id);
			$result	= mysql_query($sql) or die(mysql_error());

			if($row = mysql_fetch_assoc($result))
			{

				$results	= array('member_id'		=> $row['member_id'],
									'movie_id'		=> $row['movie_id'],
									'medium'		=> $row['own_dtls_medium'],
									'format'		=> $row['own_dtls_format'],
									'ratio'			=> $row['own_dtls_ratio'],
									'language'		=> $row['own_dtls_language'],
									'subtitle'		=> $row['own_dtls_subtitle'],
									'sound'			=> $row['own_dtls_sound'],
									'comment'		=> $row['own_dtls_comment'],
									'rating'		=> $row['own_rating'],
									'created'		=> $row['own_created'],
									'updated'		=> $row['own_updated'],
									'incompleted'	=> ($row['own_incomplete'] == 1 ? true : false));

			}

			return isset($results) ? $results : false;

		}

		// Return a list of details for the specific movie
		function get_movie_details($movie_id, $get_actors = false, $get_directors = false, $get_writers = false)
		{

			$sql	= $this->_pq("SELECT movie_id, movie_title, movie_imdb, movie_year, movie_image_name, movie_image_width, movie_image_height, movie_views, movie_created, movie_updated, movie_runtime, movie_also_known_as, movie_tagline, movie_plot, movie_imdb_rating, movie_rating, movie_rating_votes FROM #__movies WHERE movie_id = '%s'", $movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			if(mysql_num_rows($result) == 1 && $row = mysql_fetch_assoc($result))
			{

				// Get this movies Genres
				$sql	= $this->_pq("SELECT g.genre_id, g.genre_name FROM #__lnk_movie_genre l INNER JOIN #__genre g ON l.genre_id = g.genre_id WHERE l.movie_id = '%s' ORDER BY g.genre_name ASC", $movie_id);
				$result	= mysql_query($sql) or die(mysql_error());

				while($genre = mysql_fetch_row($result)) $genres[] = array('id' => $genre[0], 'title' => $genre[1]);

				$results	= array('id'			=> $row['movie_id'],
									'title'			=> $row['movie_title'],
									'year'			=> $row['movie_year'],
									'runtime'		=> $row['movie_runtime'],
									'tagline'		=> $row['movie_tagline'],
									'plot'			=> $row['movie_plot'],
									'imdb_rating'	=> $row['movie_imdb_rating'],
									'also_known_as'	=> (!empty($row['movie_also_known_as'])) ? explode("\n", $row['movie_also_known_as']) : array(),
									'genres'		=> isset($genres) ? $genres : false,
									'imdb'			=> $row['movie_imdb'],
									'imdb_url'		=> $this->imdb_url($row['movie_imdb']),
									'image_name'	=> $row['movie_image_name'],
									'image_width'	=> $row['movie_image_width'],
									'image_height'	=> $row['movie_image_height'],
									'rating'		=> $row['movie_rating'],
									'rating_votes'	=> $row['movie_rating_votes'],
									'member_vote'	=> $this->get_movie_member_vote($movie_id),
									'views'			=> $row['movie_views'],
									'created'		=> $row['movie_created'],
									'updated'		=> $row['movie_updated'],
									'actors'		=> ($get_actors ? $this->get_cast_actors_from_movie($movie_id) : false),
									'directors'		=> ($get_directors ? $this->get_cast_directors_from_movie($movie_id) : false),
									'writers'		=> ($get_writers? $this->get_cast_writers_from_movie($movie_id) : false));

			}

			return isset($results) ? $results : false;

		}

		// Get the value a member voted for a particular movie. if no member_id assigned use the current member
		function get_movie_member_vote($movie_id, $member_id = null)
		{

			if($member_id === null) $member_id = $this->security->dtls['id'];

			// Query time
			$sql	= $this->_pq("SELECT rating_value FROM #__ratings WHERE movie_id = %s AND member_id = %s", (int)$movie_id, (int)$member_id);
			$result	= mysql_query($sql) or die(mysql_error());

			if($row = mysql_fetch_assoc($result))
			{
				// we have a vote value
				$results	= $row['rating_value'];
			}

			return isset($results) ? $results : false;

		}

		function movie_own($movie_id, $member_id, $return_own_id = false)
		{

			// Returns true/false based if the member_id owns a copy of the selected movie
			$sql	= $this->_pq("SELECT own_id FROM #__own WHERE member_id = %s AND movie_id = %s", (int)$member_id, (int)$movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			$ret	= $return_own_id ? (int)mysql_result($result, 0, 0) : true;

			return (mysql_num_rows($result) == 1) ? $ret : false;

		}

		// returns the details of the members copy of a selected movie
		function movie_own_details($movie_id, $member_id)
		{
			$sql	= $this->_pq("SELECT `own_dtls_medium` , `own_dtls_format` , `own_dtls_ratio` , `own_dtls_language` , `own_dtls_subtitle` , `own_dtls_sound` , `own_dtls_comment` , `own_rating` , `own_created` , `own_updated` , `own_incomplete` FROM `movie_own` WHERE `member_id` = %s AND `movie_id` = %s", (int)$member_id, (int)$movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			if($row = mysql_fetch_assoc($result)) {
				$results	= array('medium'		=> $row['own_dtls_medium'],
									'format'		=> $row['own_dtls_format'],
									'ratio'			=> $row['own_dtls_ratio'],
									'subtitle'		=> $row['own_dtls_subtitle'],
									'sound'			=> $row['own_dtls_sound'],
									'comment'		=> $row['own_dtls_comment'],
									'rating'		=> $row['own_rating'],
									'created'		=> $row['own_created'],
									'updated'		=> $row['own_updated'],
									'incomplete'	=> ($row['own_incomplete'] == '1' ? true : false));
			}

			return isset($results) ? $results : false;
		}

		function movie_wishlist($movie_id, $member_id, $own = true)
		{

			// Returns true/false based if the member_id has a copy of the movie on their wishlist. If the movie is owned (but not in wishlist obviously), then the $own var is returned
			$sql	= $this->_pq("SELECT COUNT(member_id) FROM #__wishlist WHERE member_id = %s AND movie_id = %s", (int)$member_id, (int)$movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			$wish	= (mysql_result($result, 0, 0) == 1) ? true : false;

			if($this->movie_own($movie_id, $member_id) === true) $wish = $own;

			return $wish;


		}

		function number_of_movies()
		{
			static $num = false;
			if(!$num) {
				$sql	= $this->_pq("SELECT COUNT(movie_id) FROM #__movies");
				$result	= mysql_query($sql) or die(mysql_error());
				$num	= mysql_result($result, 0, 0);
			}
			return $num;
		}

		// obtain a list of owners of a particular movie
		function get_movie_owned_by($movie_id)
		{

			// Returns the all the owners for a particular movie (id)
			$sql	= $this->_pq("SELECT m.member_id, m.member_username, m.member_email, m.last_login, m.updated, m.movie_count, o.own_dtls_medium, o.own_id FROM #__own o INNER JOIN #__member m ON o.member_id = m.member_id WHERE o.movie_id = %s AND m.member_active = '1' AND m.member_approved = '1' AND m.member_approved_date > 0", $movie_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'		=> $row['member_id'],
									'username'	=> $row['member_username'],
									'email'		=> $row['member_email'],
									'login'		=> $row['last_login'],
									'updated'	=> $row['updated'],
									'movies'	=> $row['movie_count'],
									'medium'	=> $row['own_dtls_medium'],
									'own_id'	=> $row['own_id']);

			}

			return isset($results) ? $results : false;

		}

		// get a random movie, and its details
		function get_movie_random($image = false)
		{

			$where = array();

			// if _CUR_MOVIE is defined, it stores movie_id's not to be part of the random search, if | exists in the string, multiple movies exists
			if(defined('_CUR_MOVIE'))
			{

				$m = strpos(_CUR_MOVIE, '|') ? str_replace('|', ',', _CUR_MOVIE) : _CUR_MOVIE;

				$where[]	= "movie_id NOT IN ($m)";

			}

			// do we want a random movie with an image only?
			if($image)
			{

				$where[]	= "movie_image_name != ''";

			}

			$where	= count($where) > 0 ? "WHERE ". implode(" AND ", $where) : null;

			$sql	= $this->_pq("SELECT movie_id, movie_title, movie_imdb, movie_year, movie_image_name, movie_image_width, movie_image_height, movie_views, movie_created FROM #__movies $where ORDER BY RAND() LIMIT 1");
			$result	= mysql_query($sql) or die(mysql_error());

			if(mysql_num_rows($result) && $row = mysql_fetch_array($result))
			{

				$image_path				= _BASE_PATH . $this->config['directory_imdb_image'] . $row['movie_image_name'];

				$results	= array('id'			=> $row['movie_id'],
									'title'			=> $row['movie_title'],
									'year'			=> $row['movie_year'],
									//'genres'		=> isset($genres) ? $genres : false,
									'imdb'			=> $row['movie_imdb'],
									'imdb_url'		=> $this->imdb_url($row['movie_imdb']),
									'image'			=> ($this->config['show_image'] == 1 && !empty($row['movie_image_name']) && file_exists($image_path)) ? true : false,
									'image_name'	=> $row['movie_image_name'],
									'image_width'	=> $row['movie_image_width'],
									'image_height'	=> $row['movie_image_height'],
									'views'			=> $row['movie_views'],
									'created'		=> $row['movie_created']);

			}

			return isset($results) ? $results : false;

		}

		// returns a list of recently added movies
		function get_movies_recent($limit = 10)
		{

			$member_id	= (int)$this->security->dtls['id'];

			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, m.movie_year, m.movie_imdb, m.movie_created, o.own_id AS own, w.member_id FROM #__movies m LEFT OUTER JOIN #__own o ON m.movie_id = o.movie_id AND o.member_id = %s LEFT OUTER JOIN #__wishlist w ON m.movie_id = w.movie_id AND w.member_id = %s ORDER BY m.movie_created DESC LIMIT %s", $member_id, $member_id, (int)$limit);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'		=> $row['movie_id'],
									'title'		=> $row['movie_title'],
									'year'		=> $row['movie_year'],
									'imdb'		=> $row['movie_imdb'],
									'imdb_url'	=> $this->imdb_url($row['movie_imdb']),
									'created'	=> date($this->config['date_format_short'], $row['movie_created']),
									'own'		=> ($row[5] != null ? true : false),
									'wishlist'	=> ($row[6] > 0 ? true : false));

			}

			return isset($results) ? $results : false;

		}

		// Return an array of movies people wish to borrow from the provided members collection (owner) or get a list of open requests send from the selected member (borrower)
		function get_request_borrow($member_id, $type = 'owner')
		{

			if($type == 'owner')
			{

				$type = "b.owner_id";

			}
			else
			{

				$type = "b.borrower_id";

			}

			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, m.movie_year, mem.member_id, mem.member_username, mem.member_email, b.borrow_request_date FROM #__movies m INNER JOIN #__borrow b ON m.movie_id = b.movie_id INNER JOIN #__member mem ON b.borrower_id = mem.member_id WHERE $type = '%s' AND b.borrow_status = 'request' AND mem.member_active = '1'", (int)$member_id);
			//echo $this->_debug_sql();
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'				=> $row['movie_id'],
									'title'				=> $row['movie_title'],
									'year'				=> $row['movie_year'],
									'member_id'			=> $row['member_id'],
									'member_username'	=> $row['member_username'],
									'member_email'		=> $row['member_email'],
									'requested'			=> $row['borrow_request_date']);

			}

			return isset($results) ? $results : false;

		}

		function get_search($search_term, $filter = null)
		{

			if(!empty($search_term))
			{

				$where		= array();

				if($filter !== null) {
					$where[] = $this->_sql_filter('m.movie_title', $filter);

				}

				$member_id	= $this->security->dtls['id'];

				$where	= (count($where) > 0) ? "AND ". implode(" AND ", $where) : null;
				$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, COUNT(o.member_id) AS count, o2.member_id as owned, m.movie_year, m.movie_imdb FROM #__movies m LEFT OUTER JOIN #__own o ON m.movie_id = o.movie_id LEFT OUTER JOIN #__own o2 ON m.movie_id = o2.movie_id AND o2.member_id = %s WHERE m.movie_title LIKE '%%%s%%' $where GROUP BY m.movie_id", $member_id, $search_term);
				$result	= mysql_query($sql) or die(mysql_error());

				while($row = mysql_fetch_array($result))
				{

					$results[]	= array('id'		=> $row['movie_id'],
										'title'		=> $row['movie_title'],
										'owners'	=> $row['count'],
										'owned'		=> $row[3] > 0 ? true : false,
										'year'		=> $row['movie_year'],
										'imdb'		=> $row['movie_imdb'],
										'imdb_url'	=> $this->imdb_url($row['movie_imdb']));

				}

			}

			return isset($results) ? $results : false;

		}

		function get_welcome_stats()
		{

			$stats = array();

			$member_id	= $this->security->dtls['id'];

			// Movies in 'your' collection
			$sql	= $this->_pq("SELECT COUNT(m.movie_id) FROM #__movies m INNER JOIN #__own o ON m.movie_id = o.movie_id WHERE member_id = '$member_id'");
			$result	= mysql_query($sql) or die(mysql_error());
			$num_c	= mysql_result($result, 0, 0);

			// Movies existing in db
			$num_t	= $this->number_of_movies();

			// Total Movies Owned
			$sql	= $this->_pq("SELECT COUNT(movie_id) FROM #__own");
			$result	= mysql_query($sql) or die(mysql_error());
			$num_o	= mysql_result($result, 0, 0);

			$stats['collection']	= $num_c;
			$stats['total']			= $num_t;
			$stats['owned']			= $num_o;
			$stats['online']		= count($this->get_whos_online());
			$wishlist				= $this->get_wishlist();
			$stats['wishlist']		= count($wishlist == false ? null : $wishlist);

			return $stats;

		}

		// returns an array of members who had some activity within the last x minutes
		function get_whos_online()
		{

			$time	= time() - ((int)$this->config['session_time'] * 60); // Sessions last 15 minutes

			$sql	= $this->_pq("SELECT DISTINCT m.member_id, m.member_username, m.member_email, m.member_active, m.member_approved, m.member_approved_date, m.referer_id, m.last_login, m.movie_count, m.is_referer FROM #__session s INNER JOIN #__member m ON s.member_id = m.member_id WHERE s.session_active = '1' AND s.session_last_action > '%s'", $time);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'			=> (int)$row['member_id'],
									'username'		=> $row['member_username'],
									'email'			=> $row['member_email'],
									'active'		=> (int)$row['member_active'] == 1 ? true : false,
									'approved'		=> (int)$row['member_approved'] == 1 ? true : false,
									'approve_date'	=> (int)$row['member_approved_date'],
									'referer'		=> (int)$row['referer_id'],
									'last_login'	=> (int)$row['last_login'],
									'movie_count'	=> (int)$row['movie_count'],
									'is_referer'	=> (int)$row['is_referer']);

			}

			return isset($results) ? $results : false;

		}

		function get_wishlist() {

			$member_id	= $this->security->dtls['id'];

			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title FROM #__wishlist w INNER JOIN #__movies m ON w.movie_id = m.movie_id WHERE w.member_id = '%s'", $member_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'	=> $row['movie_id'],
									'title'	=> $row['movie_title']);

			}

			return isset($results) ? $results : false;

		}

		function get_wishlist_available()
		{

			$member_id	= $this->security->dtls['id'];

			// Returns a list of movies (and owner details) of movies in your wishlist that other people own
			$sql	= $this->_pq("SELECT m.movie_id, m.movie_title, m.movie_year FROM #__own o INNER JOIN #__wishlist w ON o.movie_id = w.movie_id INNER JOIN #__movies m ON o.movie_id = m.movie_id WHERE o.member_id != '%s' AND w.member_id = '%s' GROUP BY m.movie_id", $member_id, $member_id);
			$result	= mysql_query($sql) or die(mysql_error());

			while($row = mysql_fetch_array($result))
			{

				$results[]	= array('id'		=> $row['movie_id'],
									'title'		=> $row['movie_title'],
									'year'		=> $row['movie_year']);

			}

			return isset($results) ? $results : false;

		}

		// find out if the selected member has requested, or is currently borrowing the selected movie copy
		// returns bool
		function is_borrowing($own_id, $borrower_id)
		{

			$sql	= $this->_pq("SELECT COUNT(movie_id) FROM #__borrow WHERE own_id = %s AND borrower_id = %s AND borrow_status IN ('request', 'borrowed')", $own_id, $borrower_id);
			$result	= mysql_query($sql) or die(mysql_error());

			return mysql_result($result, 0, 0) != 0 ? true : false;


		}

		// updates the selected movie from imdb
		function update_movie($movie_id)
		{

			// Update the selected movies details from IMDB
			$movie_id = (int)$movie_id;

			$member_id	= $this->security->dtls['id'];


			// Movie Exists?
			$movie = $this->get_movie_details($movie_id);

			if($movie) {

				$imdb	= $movie['imdb'];

				$movie	= $this->obtain_movie_imdb($imdb, true);
				if($movie) {

					$image	= null;

					if(isset($movie['image']) && $this->config['save_image'] == 1) {
						// If there is an image available & save_image is on, then update the cover
						$image = $this->imdb_save_image($movie['image'], $imdb);
						$image = sprintf(", movie_image_name = '%s', movie_image_width = '%s', movie_image_height = '%s'", $image['filename'], $image['width'], $image['height']);
					}

					$also_known_as	= trim(implode("\n", $movie['also_known_as']));

					// Update the movie
					$sql	= $this->_pq("UPDATE #__movies SET movie_title = '%s', movie_year = '%s', movie_updated = UNIX_TIMESTAMP(), movie_updated_by = '%s', movie_runtime = '%s', movie_also_known_as = '%s', movie_tagline = '%s', movie_plot = '%s', movie_imdb_rating = '%s' $image WHERE movie_id = '%s'", $movie['title'], $movie['year'], $member_id, $movie['runtime'], $also_known_as, $movie['tagline'], $movie['plot'], $movie['rating'], $movie_id);
					$result	= mysql_query($sql) or die(mysql_error());

					if($result) {
						// Add the acting cast
						$sql	= $this->_pq("DELETE FROM #__lnk_movie_actors WHERE movie_id = %s", $movie_id);
						$result	= mysql_query($sql) or die(mysql_error());

						if(isset($movie['cast'])) {
							foreach($movie['cast'] as $c) {
								if(($act_id = $this->add_cast_member($c['imdb_id'], $c['name'])) !== false) {
									$sql	= $this->_pq("INSERT INTO #__lnk_movie_actors (movie_id, name_id, mc_character_name, mc_credited_as) VALUES (%s, %s, '%s', '%s');", $movie_id, $act_id, $c['character'], $c['name']);
									$result	= mysql_query($sql) or die(mysql_error());
								}
							}
						}

						// Add the directors
						$sql	= $this->_pq("DELETE FROM #__lnk_movie_directors WHERE movie_id = %s", $movie_id);
						$result	= mysql_query($sql) or die(mysql_error());

						if(isset($movie['directors'])) {
							foreach($movie['directors'] as $d) {
								if(($director_id = $this->add_cast_member($d['imdb_id'], $d['name'])) !== false) {
									$sql	= $this->_pq("INSERT INTO #__lnk_movie_directors (movie_id, name_id, md_credited_as) VALUES (%s, %s, NULL);", $movie_id, $director_id);
									$result	= mysql_query($sql) or die(mysql_error());
								}
							}
						}

						// Add the writers
						$sql	= $this->_pq("DELETE FROM #__lnk_movie_writers WHERE movie_id = %s", $movie_id);
						$result	= mysql_query($sql) or die(mysql_error());

						if(isset($movie['writers'])) {
							foreach($movie['writers'] as $w) {
								if(($writer_id = $this->add_cast_member($w['imdb_id'], $w['name'])) !== false) {
									$sql	= $this->_pq("INSERT INTO #__lnk_movie_writers (movie_id, name_id, mw_credited_as, mw_role) VALUES(%s, %s, NULL, '%s')", $movie_id, $writer_id, $w['role']);
									$result	= mysql_query($sql) or die(mysql_error());
								}
							}
						}

						// Remove Genres, and read them

						$this->update_genre_movie_count();
						return true;

					} else {
						// Could not update the database
					}
				} else {
					// Unable to retrieve movie details from IMDB
				}
			} else {
				// Selected movie does not exist
			}
			return false;
		}

		// updates `genre_movie_count in #__genre table (this is to help boost performance in large databases)
		function update_genre_movie_count($genre_id = null)
		{

			// Update the genre_movie_count. if genre_id(s) are provided it will only update the selected genres
			$where	= array();

			if(is_numeric($genre_id) && $genre_id > 0) {
				$where[]	= "genre_id = ". (int)$genre_id;
			} elseif(is_array($genre_id)) {
				$where[]	= "genre_id IN (". addslashes(implode(",", $genre_id)).")";
			}

			$where	= (count($where) > 0) ? "WHERE ". implode(" AND ", $genre_id) : null;

			$sql	= $this->_pq("SELECT genre_id FROM #__genre $where ORDER BY genre_id");
			$result	= mysql_query($sql) or die(mysql_error());

			$count	= 0;

			while($row = mysql_fetch_row($result)) {
				// Locate all movies for this genre, and update
				$sql	= $this->_pq("SELECT COUNT(DISTINCT movie_id) FROM #__lnk_movie_genre WHERE genre_id = %s", (int)$row[0]);
				$res	= mysql_query($sql) or die(mysql_error());
				$num	= (int)mysql_result($res, 0, 0);
				$row[0] .': '. $num .'<br />';

				$sql	= $this->_pq("UPDATE #__genre SET genre_movie_count = %s WHERE genre_id = %s", $num, (int)$row[0]);
				$res	= mysql_query($sql) or die(mysql_error());

				if($res) $count++;
			}
			return (mysql_num_rows($result) == $count && $count > 0) ? true : false;
		}

		function update_member_movie_count($member_id)
		{

			// Update the movie count of the selected member
			$movies = $this->get_member_movies($member_id);

			if($movies !== false)
			{

				// Update the users account with the number of movies in their collecion
				$num_movies	= (int)count($movies);

				$sql	= $this->_pq("UPDATE #__member SET movie_count = %s WHERE member_id = %s", $num_movies, $member_id);
				$result	= mysql_query($sql) or die(mysql_error());

				if($result) return true;

			}

			return false;

		}

		// Updates the movie_rating & movie_rating_votes fields based on the current member ratings
		function update_movie_ratings($movie_id, $get_stats = false)
		{

			// Number of min votes required before results are compiled
			//$min_votes = (int)$this->config['ratings_min_votes'];

			// Get the sum of all votes + count of how many records there are for this movie
			// Note: we do not need to check currently if the member_id is active or not, their votes are still counted
			$sql	= $this->_pq("SELECT SUM(rating_value) `value`, COUNT(rating_id) `count` FROM #__ratings WHERE movie_id = %s", (int)$movie_id);
			$result = mysql_query($sql) or die(mysql_error());

			if($row = mysql_fetch_assoc($result))
			{

				// Compile Results
				$rating	= round($row['value'] / $row['count'], 2);
				$votes	= $row['count'];

				$sql	= $this->_pq("UPDATE #__movies SET movie_rating = %s, movie_rating_votes = %s WHERE movie_id = %s", (float)$rating, (int)$votes, (int)$movie_id);
				$result	= mysql_query($sql) or die(mysql_error());

				return $result ? ($get_stats ? array('rating' => $rating, 'votes' => $votes) : true) : false;

			}

			return false;

		}

		//update the selected members movie count
		/*function update_member_movie_count($member_id) 
		{
			// get the number of movies
			$sql	= $this->_pq("SELECT COUNT(DISTINCT `movie_id`) FROM `#__own` WHERE `member_id` = %s", $member_id);
			$result	= mysql_query($sql) or die(mysql_error());
			$num	= mysql_result($result, 0, 0);
			
			if(is_numeric($num)) {
				// update the number of movies
				$sql	= $this->_pq("UPDATE `#__member` SET `updated` = UNIX_TIMESTAMP(), `movie_count` = %s WHERE `member_id` = %s", (int)$num, $member_id);
				$result	= mysql_query($sql) or die(mysql_error());
				
				// return the number of movies for this user
				return $num;
			}			
			
			return false;
		}*/
		
		function imdb_save_image($url, $id)
		{

			$f		= fopen($url, 'r');
			$image	= null;

			if($f)
			{

				while(!@feof($f)) $image .= fgets($f, 1024);

				fclose($f);

				if(strlen($image) > 0)
				{

					// We have the image.. now lets save it

					$ext = substr($url, strrpos($url, '.') + 1);

					$save_path	= _BASE_PATH . $this->config['directory_imdb_image'];
					$save_file	= _BASE_PATH . $this->config['directory_imdb_image'] . $id .'.'. $ext;
					$file_name	= $id .'.'. $ext;

					if(!file_exists($save_path))
					{

						// Image save directory doesnt exist. Create it
						mkdir($save_path, 0777);

					}

					if(file_exists($save_file))
					{

						// Remove old file if it exists
						unlink($save_file);

					}

					touch($save_file, 0777);

					$f	= fopen($save_file, 'w');

					if($f)
					{

						$write	= fwrite($f, $image, strlen($image));

						fclose($f);

						if($write)
						{

							list($width, $height, $type) = getimagesize($save_file);

							return array('filename'	=> $file_name,
										'width'		=> $width,
										'height'	=> $height);

						}

					}

				}

			}

			return false;

		}

		function imdb_search_movie_title($title)
		{

			// This function executes IMDB's search. We then gather the popular results for this search & return them in a useable array
			$url	= str_replace('%%', urlencode(trim($title)), $this->config['imdb_search']);

			$f = fopen($url, 'r');

			$data	= null;

			if($f)
			{

				while(!@feof($f)) $data .= fgets($f, 2048);

				if(!empty($data))
				{

					$search	= array();

					// Are we at a search page? or was their only 1 result and have we been auto redirected?
					if(is_numeric(strpos($data, '<title>IMDb  Search</title>')))
					{

						// Find all valid urls
						preg_match_all("/<a href=\"\/title\/(tt[\d]+)\/\"(?:[^>]*)>([^<]+)<\/a> \(((?:19|20)[\d]{2})(?:[\S]*)\)([^<]*)/i", $data, $results, PREG_SET_ORDER);

						// Loop though results, and filter undesired results
						$ids	= array();

						foreach($results as $v)
						{

							// Lets make sure this isnt a video game!
							$extra	= strtolower(trim($v[4]));

							if($extra !== '(vg)' && !in_array($v[1], $ids))
							{

								$ids[]	= $v[1];

								$search[]	= array('id'		=> $v[1],
													'title'		=> $v[2],
													'year'		=> $v[3],
													'extra'		=> $extra,
													'imdb_url'	=> str_replace('%%', $v[1], $this->config['imdb_url']));

							}

						}


					}
					else
					{

						// There was 1 result only and we have been auto redirected to it
						// Get the ID of this film
						$preg	= "/href=\"\/mymovies\/list\?pending&amp;add=(\d+)/";

						preg_match($preg, $data, $id);

						if(isset($id[1]))
						{
							$imdb_id = 'tt'.$id[1];
							$dtls = $this->obtain_movie_imdb($imdb_id);

							$search[]	= array('id'		=> $imdb_id,
												'title'		=> $dtls['title'],
												'year'		=> $dtls['year'],
												'extra'		=> null,
												'imdb_url'	=> str_replace('%%', $imdb_id, $this->config['imdb_url']));

						}

					}

					return count($search) > 0 ? $search : false;

				}

				fclose($f);

			}

			// Return a -1 error code to notify that a connection couldnt be established
			return -1;

		}

		function imdb_url($id)
		{

			return str_replace('%%', $id, $this->config['imdb_url']);

		}

		function imdb_cast_url($id)
		{

			return str_replace('%%', $id, $this->config['imdb_name_url']);

		}

		function obtain_movie_imdb($id, $use_cache = true)
		{

			// this could take a while
			set_time_limit(0);

			// generate the imdb url
			$url		= str_replace('%%', $id, $this->config['imdb_url']);
			$data		= null;

			// the path to the possible cache path
			$cache_file	= _BASE_PATH . $this->config['directory_imdb_cache'] . $id .'.title';

			if($this->config['imdb_cache'] == '1' && file_exists($cache_file) && $use_cache == true) {
				// Retrieve information from cache
				$handle	= fopen($cache_file, 'r');
				if($handle) {
					while(!@feof($handle)) $data .= fgets($handle, 2048);
					fclose($handle);
				}
			} else {
				// Store the page in the cache, and return its details
				$handle = fopen($url, 'r');
				if($handle) {
					while(!@feof($handle)) $data .= fgets($handle, 2048);
					fclose($handle);

					// Obtain the data
					if($this->config['imdb_cache'] == '1' && !empty($data)) {
						// Cache these details
						if(file_exists($cache_file)) {
							@unlink($cache_file);
						}

						$handle	= fopen($cache_file, 'w');

						if($handle) {
							fwrite($handle, str_replace("\r\n", "\n", $data), strlen($data));
							fclose($handle);
						}
					}
				} else {
					// Could not establish a connection

				}
			}

			if(!strstr($data, 'Page not found') || strlen($data) > 0) {// Lets make sure this isnt a 404 page (the movie url doesnt exist for example!)
				// Start filtering data
				$return = array();
				//$data = preg_replace("/(\r|\n+)/", null, $data);

				// =----------------------------------------------------=
				// Get Title
				$preg	= "/<h1>([^<]*)([\D]*)(\d{4})/m";
				preg_match($preg, $data, $_title);
				if(isset($_title[1])) {
					$return['title'] = trim($_title[1]);
					$return['year']	= $_title[3];
					$title	= trim($_title[1]);
				}

				unset($preg, $_title);

				// Get Movie Cover
				$preg	= "/<a name=\"poster\"(?:[^>]*)><img(?:.*)src=\"([^\"]+)\"/";
				preg_match($preg, $data, $cover);

				if(isset($cover[1])) {
					$return['image']	= $cover[1];
				}

				// =----------------------------------------------------=
				// Get Director
				$str	= '<h5>Director:</h5>'."\n";

				if(strpos($data, $str)) {
					$pos	= strpos($data, $str) + strlen($str);

					$tmp	= substr($data, $pos, strpos($data, "\n", $pos) - $pos);

					$preg	= "/<a href=\"\/name\/(nm[\d]+)\/\">([^<]*)<\/a>/i";
					preg_match_all($preg, $tmp, $director, PREG_SET_ORDER);

					if(is_array($director) && count($director)) {
						foreach($director as $v) {
							$return['directors'][]	= array('imdb_id'	=> $v[1],
															'name'		=> $v[2]);
						}
					}
				}

				unset($director, $preg);

				// =----------------------------------------------------=
				// Get Written By
				$str = '<h5>Writers';

				if(strpos($data, $str)) {
					$pos	= strpos($data, $str) + strlen($str);

					$tmp	= substr($data, $pos, strpos($data, '</td>', $pos) - $pos);

					$preg	= "/<a href=\"\/name\/(nm[\d]+)\/\">([^<]*)<\/a> \(([^\)]*)\)/i";
					preg_match_all($preg, $tmp, $writers, PREG_SET_ORDER);

					if(is_array($writers) && count($writers)) {
						foreach($writers as $v) {
							$return['writers'][]	= array('imdb_id'	=> $v[1],
															'name'		=> $v[2],
															'role'		=> $v[3]);
						}
					}
				}

				unset($preg, $writers);

				// =----------------------------------------------------=
				// Get Tagline
				$preg	= "/<h5>Tagline:<\/h5>\s([^<]+)/i";
				preg_match($preg, $data, $_match);

				$return['tagline'] = (isset($_match[1])) ? trim($_match[1]) : null;

				// =----------------------------------------------------=
				// Get Plot Outline
				$preg	= "/<h5>Plot Outline:<\/h5>\s([^<]+)/i";
				preg_match($preg, $data, $_match);

				$return['plot'] = (isset($_match[1])) ? trim($_match[1]) : null;

				// =----------------------------------------------------=
				// Get IMDb Rating
				$preg	= "/<b>User Rating:<\/b>(?:\s*)<b>(\d\.\d)\/10<\/b>(?:\s*)<small>\(<a href=\"ratings\">([\d,]+) votes<\/a>\)<\/small>/i";
				preg_match($preg, $data, $_match);

				$return['rating']	= (isset($_match[1])) ? $_match[1] : 0;

				// =----------------------------------------------------=
				// Get Cast
				$pos	= strpos($data, 'Cast overview');
				$cast	= substr($data, $pos, strpos($data, '<a class="tnl5more" href="fullcredits#cast">(more)</a>', $pos) + $pos);
				$cast	= str_replace('</tr>', '</tr>'."\n", $cast);
				//$preg	= "/<tr><td valign=\"top\"><a href=\"\/name\/(nm[\d]{7})\/\">([^<]{0,})<\/a><\/td><td valign=\"top\" nowrap=\"1\"> .... <\/td><td valign=\"top\">([^<]{0,})<\/td><\/tr>/i";
				$preg	= "/<tr class=\"(?:odd|even)\"><td class=\"hs\"><a href=\"(?:[^\"]*)\">(?:.*)<\/a><br><\/td><td class=\"nm\"><a href=\"\/name\/(nm[\d]+)\/\">([^<]*)<\/a><\/td><td class=\"ddd\"> ... <\/td><td class=\"char\">([^<]+)<\/td><\/tr>/i";

				preg_match_all($preg, $cast, $actors, PREG_SET_ORDER);
				if(is_array($actors) && count($actors)) {
					foreach($actors as $v) {
						$return['cast'][]	= array('imdb_id'	=> $v[1],
													'name'		=> $v[2],
													'character'	=> $v[3]);
					}
				}

				unset($preg, $cast, $actors);

				// =----------------------------------------------------=
				// Get Also Known As
				$preg	= "/<h5>Also Known As:<\/h5>([^\n]*)/";
				preg_match($preg, $data, $also);

				if(isset($also[1])) {
					$also[1] = trim($also[1]);

					$preg	= "/([^<]*)<br>/";

					preg_match_all($preg, $also[1], $also);

					$return['also_known_as'] = $also[1];
				} else {
					$return['also_known_as'] = array();
				}

				unset($preg, $also);

				// =----------------------------------------------------=
				// Get Genres
				$preg	= "/<h5>Genre:<\/h5>\s(.*)<a class=\"tn15more inline\"/";

				preg_match($preg, $data, $genres);
				if(isset($genres[1])) {
					$genres[1] = trim($genres[1]);

					$preg	= "/<a href=\"(?:[^\"]+)\">([^<]+)<\/a>/";

					preg_match_all($preg, $genres[1], $genre);

					// Array of genres
					$genres	= $genre[1];
					unset($genre, $preg);

					foreach($genres as $v) {

						// Search though db for genre id
						$sql	= $this->_pq("SELECT genre_id FROM #__genre WHERE genre_name = '$v' LIMIT 1");
						$result	= mysql_query($sql) or die(mysql_error());

						if(mysql_num_rows($result) == 1) {
							$return['genre'][mysql_result($result, 0, 0)]	= $v;
						}
					}
				}
				unset($preg, $genres, $genre);
				// =----------------------------------------------------=
				// Runtime
				$preg	= "/<h5>Runtime:<\/h5>\n([\d]{1,}) min/";
				preg_match($preg, $data, $_match);

				$return['runtime']	= (isset($_match[1])) ? $_match[1] : 0;

				// debug
				//echo '<pre>';
				//print_r($return);exit;

				unset($preg, $_match);
				// return our huge array
				return $return;

			}
		}

		function save_config($k, $v)
		{

			// This function updates/saves the config option in the db
			$sql	= $this->_pq("UPDATE #__config SET config_value = '%s' WHERE config_key = '%s';", $v, $k);
			$result	= mysql_query($sql) or die(mysql_error());

			return $result ? true : false;

		}

		// take the supplied comment details & save them correctly
		function save_comment($movie_id, $member_id, $comment)
		{

			// we will asume comment is raw data from a textarea, or other input device
			// strip all html tags & convert <>'" into their html entities
			$comment	= htmlentities(strip_tags($comment));

			$sql	= $this->_pq("INSERT INTO #__comment (movie_id, member_id, comment_data, comment_active, comment_created) VALUES (%s, %s, '%s', 1, UNIX_TIMESTAMP());", (int)$movie_id, (int)$member_id, $comment);
			$result	= mysql_query($sql) or die(mysql_error());

			return ($result) ? mysql_insert_id() : false;

		}

		// builds a new single dimentional array from an existing array
		// the key/value of the new array are build up from values within the existing array

		function _convert_array(&$array, $key, $value)
		{

			// takes the suppied array, and its 'key' and 'value' (values within the array), and makes a new array from them
			$ret	= array();

			foreach($array as $v)
			{

				if(isset($v[$key]))
				{

					$ret[$v[$key]]	= isset($v[$value]) ? $v[$value] : null;

				}
				elseif($key == null)
				{

					$ret[] = isset($v[$value]) ? $v[$value] : null;

				}

			}

			return $ret;

		}

		// This function returns the previously entered query (_pq) and returns it in a debug friendly format
		function _debug_sql()
		{

			$sql = str_replace("FROM", "\nFROM", $this->sql);
			$sql = str_replace("INNER JOIN", "\nINNER JOIN", $sql);
			$sql = str_replace("ON", "\nON", $sql);
			$sql = str_replace("WHERE", "\nWHERE", $sql);
			$sql = str_replace("AND", "\nAND", $sql);
			$sql = str_replace("GROUP BY", "\nGROUP BY", $sql);
			$sql = str_replace("ORDER BY", "\nORDER BY", $sql);
			$sql = str_replace("LIMIT", "\nLIMIT", $sql);

			return '<textarea cols="80" rows="12">'. $sql .'</textarea>';

		}

		function _pq($sql)
		{

			$prefix		= $this->_parse_prefix;
			$sql		= trim($sql);

			$len		= strlen($sql);
			$pre_len	= strlen($prefix);

			$in_string	= false;
			$escaped	= false;
			$quote_char	= null;

			$return		= null;

			$args		= array_slice(func_get_args(), 1);

			if(is_array($args) && count($args) > 0)
			{

				if(is_array($args[0]))
				{

					$args = $args[0];

				}

				$func		= function_exists('mysql_real_escape_string') ? 'mysql_real_escape_string' : 'addslashes';
				$args		= array_map($func, $args);
				unset($func);

			}

			for($i = 0; $i < $len; $i++)
			{

				$c		= $sql{$i};
				$tmp	= substr($sql, $i, $pre_len);

				if(!$in_string && ($c == '\'' || $c == '"'))
				{

					$in_string	= true;
					$escaped	= false;
					$quote_char = $c;

				}
				else
				{

					if($c == $quote_char && !$escaped)
					{

						$in_string	= false;

					}
					elseif($c == '\\' && !$escaped)
					{

						$escaped	= true;

					}
					else
					{

						$escaped	= false;

					}

				}

				if($tmp == $prefix && !$in_string)
				{

					$return .= $this->_prefix;
					$i += ($pre_len - 1);

				}
				else
				{

					$return .= $c;

				}

			}

			$this->sql	= count($args) > 0 ? vsprintf($return, $args) : $return;

			$this->queries[] = $this->sql;

			return $this->sql;

		}

		function _print_r($array, $remove_html = false)
		{

			if(is_array($array))
			{

				if($remove_html) $array = array_map('strip_tags', $array);

				echo '<pre>';
				print_r(array_map('htmlentities', $array));
				echo '</pre>';

			}
			else
			{

				echo $array;

			}

		}

		// builds up a valid SQL string to filter the supplied field based on the filter
		function _sql_filter($field, $filter)
		{
			$filter = trim($filter);
			if(!empty($field) && !empty($filter))
			{
				if(preg_match("/^[a-z]$/", $filter)) {
					return "LEFT(".$field.", 1) = '". $filter ."'";
				} else {
					return "LEFT(".$field .", 1) REGEXP '([^a-z])'";
				}
			}
			return null;
		}

		function _debug()
		{
			$args = func_get_args();
			echo '<textarea style="width: 50%; height: 400px;">';
			foreach($args as $v) {
				if(is_array($v)) {
					print_r($v);
				} else {
					var_dump($v);
				}
			}
			//array_map('print_r', $args);
			echo '</textarea>';
		}
		
	}

	function remove_gpc_slashes($v)
	{

		// Recersive function that removes slashes from array. Used when magic_quote_gpc() is on

		return is_array($v) ? array_map('remove_gpc_slashes', $v) : stripslashes($v);

	}


?>